package com.example.jsd2205.vx.emos.controller;


import cn.hutool.json.JSONUtil;
import com.example.jsd2205.vx.emos.common.util.R;
import com.example.jsd2205.vx.emos.config.shiro.JwtUtil;
import com.example.jsd2205.vx.emos.config.tencent.TLSSigAPIv2;
import com.example.jsd2205.vx.emos.controller.form.*;
import com.example.jsd2205.vx.emos.exception.EmosException;
import com.example.jsd2205.vx.emos.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.List;


/**
 * 处理移动端提交的请求
 * @author admin兰
 */
@RestController
@RequestMapping("/user")
@Api("用户模块Web接口")
public class UserController {
    @Autowired
    private UserService userService;
    //业务层的引用
    @Autowired
    private JwtUtil jwtUtil;
    //生成令牌字符串
    @Autowired
    private RedisTemplate redisTemplate;
    //服务端要在缓存
    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;
    //缓存令牌的过期时间

    /**
     *腾讯TRTC服务相关值注入
     */
    @Value("${trtc.appid}")
    private Integer appid;

    @Value("${trtc.key}")
    private String key;

    @Value("${trtc.expire}")
    private Integer expire;



    @PostMapping("/register")
    @ApiOperation("注册用户")
    public R register(@Valid @RequestBody RegisterForm form){
        int id=userService.registerUser(form.getRegisterCode(),form.getCode(),form.getNickname(),form.getPhoto());
        String token=jwtUtil.createToken(id);
        Set<String> permsSet=userService.searchUserPermissions(id);
        //得到用户的权限列表
        saveCacheToken(token,id);
        return R.ok("用户注册成功").put("token",token).put("permission",permsSet);
        //客户端返回用户注册成功
    }

    @PostMapping("/login")
    @ApiOperation("登陆系统")
    public R login(@Valid @RequestBody LoginForm form){
        int id=userService.login(form.getCode());
        String token=jwtUtil.createToken(id);
        saveCacheToken(token,id);
        Set<String> permsSet = userService.searchUserPermissions(id);
        return R.ok("登陆成功").put("token",token).put("permission",permsSet);
    }

    /**
     * 查询用户摘要信息
     * @param token
     * @return R
     */
    @GetMapping("/searchUserSummary")
    @ApiOperation("查询用户摘要信息")
    public R searchUserSummary(@RequestHeader("token") String token){
        int userId=jwtUtil.getUserId(token);
        HashMap map=userService.searchUserSummary(userId);
        return R.ok().put("result",map);
    }

    /**
     * 查询员工列表，按照部门分组排列
     * @param form
     * @return R
     */
    @PostMapping("/searchUserGroupByDept")
    @ApiOperation("查询员工列表，按照部门分组排列")
    @RequiresPermissions(value = {"ROOT","EMPLOYEE:SELECT"},logical = Logical.OR)
    public R searchUserGroupByDept(@Valid @RequestBody SearchUserGroupByDeptForm form){
        ArrayList<HashMap> list=userService.searchUserGroupByDept(form.getKeyword());
        return R.ok().put("result",list);
    }

    private void saveCacheToken(String token,int userId){
        redisTemplate.opsForValue().set(token,userId+"",cacheExpire, TimeUnit.DAYS);
    }

    /**
     * 查询成员
     * @param form
     * @return R
     */
    @PostMapping("/searchMembers")
    @ApiOperation("查询成员")
    @RequiresPermissions(value = {"ROOT", "MEETING:INSERT", "MEETING:UPDATE"},logical = Logical.OR)
    public R searchMembers(@Valid @RequestBody SearchMembersForm form){
        if(!JSONUtil.isJsonArray(form.getMembers())){
            throw new EmosException("members不是JSON数组");
        }
        List param=JSONUtil.parseArray(form.getMembers()).toList(Integer.class);
        ArrayList list=userService.searchMembers(param);
        return R.ok().put("result",list);
    }

    /**
     * 查询用户姓名和头像
     * @param form
     * @return R
     */
    @PostMapping("/selectUserPhotoAndName")
    @ApiOperation("查询用户姓名和头像")
    @RequiresPermissions(value = {"WORKFLOW:APPROVAL"})
    public R selectUserPhotoAndName(@Valid @RequestBody SelectUserPhotoAndNameForm form){
        if(!JSONUtil.isJsonArray(form.getIds())){
            throw new EmosException("参数不是JSON数组");
        }
        List<Integer> param=JSONUtil.parseArray(form.getIds()).toList(Integer.class);
        List<HashMap> list=userService.selectUserPhotoAndName(param);
        return R.ok().put("result",list);
    }

    /**
     * 生成用户签名
     * @param token
     * @return R
     */
    @GetMapping("/genUserSig")
    @ApiOperation("生成用户签名")
    public R genUserSig(@RequestHeader("token") String token){
        int id=jwtUtil.getUserId(token);
        String email=userService.searchMemberEmail(id);
        TLSSigAPIv2 api=new TLSSigAPIv2(appid,key);
        String userSig=api.genUserSig(email,expire);
        return R.ok().put("userSig",userSig).put("email",email);
    }






}
